from django.shortcuts import render, HttpResponse
from  django.http.response  import  JsonResponse
from django.shortcuts import render,HttpResponse
from django.views import View
from .serializers import StudentSerializer,StudentModelSerializer
from students.models import Student


# Create your views here.


class StudentView(View):

    def get(self,request):
        student  = Student.objects.get(pk=3)
        serializer = StudentSerializer(instance=student)
        return  JsonResponse(serializer.data,safe=False)

    '''
    def  get(self,request):
        import  json
        data    = json.loads(request.body)
        serializer = StudentSerializer()
        print(serializer)
        #return JsonResponse(serializer.data,safe=False)
        return  HttpResponse('ok')
    '''
    def post(self, request):
        print(request.body)
        back = request.body
        import json
        # data = str(back,'utf-8')
        data = json.loads(back,strict=False)
        print('---', data)
        # print(back.decode())

        # 反序列化器
        # 1 实例化序列器对象
        serializer = StudentSerializer(data=data)
        # 2 调用验证方法
        # raise_exception 如果验证失败以后，不再执行后续的代码和操作，直接抛出错误
        ret = serializer.is_valid(raise_exception=True)  # 验证成功
        print(ret)
        # 验证通过，则有数据
        print('success', serializer.validated_data)  # 成功放入这个里面
        # 验证失败
        print('error', serializer.errors)  # 失败放入里面

        # 这里会自动调用序列化器的create或者update方法
        serializer.save()

        return HttpResponse('ok')

    # 修改数据
    def put(self, request):
        # 先获取要更新的数据对象
        data = request.body
        import json
        data = json.loads(data, strict=False)
        id = data.get('id')
        student_obj = Student.objects.get(pk=id)
        # 接受客户端的数据
        # 1 实例化序列器对象  partial=True 表示只对传入的字段做校验，没传的就不做校验
        serializer = StudentSerializer(instance=student_obj, data=data,partial=True)
        serializer.is_valid(raise_exception=True)
        # 这里会自动调用序列化器的create或者update方法
        serializer.save()

        return HttpResponse('修改成功')


#自定义序列化器
class  Student2View(View):
    def get(self, request):
        student = Student.objects.get(pk=3)
        serializer = StudentModelSerializer(instance=student)
        return JsonResponse(serializer.data, safe=False)

    def post(self, request):
        back = request.body
        import json
        data = json.loads(back,strict=False)
        # 反序列化器
        # 1 实例化序列器对象
        serializer = StudentModelSerializer(data=data)
        # 2 调用验证方法
        # raise_exception 如果验证失败以后，不再执行后续的代码和操作，直接抛出错误
        ret = serializer.is_valid(raise_exception=True)  # 验证成功
        # 这里会自动调用序列化器的create或者update方法
        instance = serializer.save()
        return JsonResponse(serializer.data,safe=False)

